package com.jiangruan.javaproject.rpc;

import com.alibaba.fastjson.JSONObject;
import com.jiangruan.javaproject.Constants;
import com.jiangruan.javaproject.bean.GetBlockCountEntity;
import com.jiangruan.javaproject.request.HttpUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:huayuzhuo
 * @email:2798866329@qq.com
 * @desc:   该类实现比特币客户端"getbestblockcount"区块数功能
 * @datatime: 2021/12/19 13:19
 */
public class GetBlockCount {

    public static int getBlockCount(){

        //准备rpc请求的用户信息及对应的base64格式
        String author = Constants.BITCOIN_RPC_USER + ":" + Constants.BITCOIN_RPC_PWD;
        Base64.Encoder encoder = Base64.getEncoder();      //base64编码
        String autthorBase64 = encoder.encodeToString(author.getBytes());

        //请求头的属性设置
        Map<String,String> header = new HashMap<>();
        header.put("Content-Type","application/json");
        header.put("Authorization","Basic "+autthorBase64);

        //准备rpc请求的数据
        Map<String,Object> body = new HashMap<>();  //Object    任意类型
        body.put("id",1002);
        body.put("method",Constants.GETBLOCKCOUNT);        //"getblockcount"
        body.put("params",null);
        body.put("json","2.0");
        byte[] byteBytes = JSONObject.toJSONBytes(body);    //将map集合 body转成数组

        String result = HttpUtils.post(Constants.BITCOIN_RPC_URL, header, byteBytes);

        //完成请求后，json化，取需要的数据
        GetBlockCountEntity getBlockCount = JSONObject.parseObject(result,GetBlockCountEntity.class);

        return getBlockCount.result;
    }
}
